<template>
  <el-dialog title="批量导入" :visible.sync="isBulkImportt" width="40%" :before-close="handleClose" :close-on-click-modal='false'>
    <el-row :gutter="24">
      <el-col :span="12" :offset="6">
        <el-upload class="upload-demo" ref="upload" :headers="headers" :action="this.Api+'/api/student/batchImportStudent'" :file-list="fileList" :auto-upload="false" accept=".xlsx" name="excel" :on-success="successResave" :on-error="errorResave" :on-change="onChangeToolFile">
          <el-button slot="trigger" icon="el-icon-upload2" size="small" type="primary" plain style="width:100%;">选择导入文件</el-button>
          <div slot="tip" class="el-upload__tip">建议大小不超过1000K，支持格式.xlsx</div>
        </el-upload>
        <br>
        <p class="uploadText">根据模版完善学生信息</p>
        <el-button size="small" icon="el-icon-download" type="primary" plain style="width:100%;" @click="downLoadFn()">点击下载学生模版</el-button>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close()">取 消</el-button>
      <el-button type="primary" @click="submitUpload">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import downloadApi from '@/common/downloadApi.js'
export default {
  props: ['isBulkImportt'],
  data () {
    return {
      fileList: [],
      Api: '',
      headers: {
        token: ''
      }
    }
  },
  created () {
    this.headers.token = window.sessionStorage.getItem('token')
    this.Api = downloadApi
  },
  methods: {
    handleClose () {
      this.$refs.upload.clearFiles()
      this.$emit('noBulkImportt')
    },
    close (type) {
      this.$refs.upload.clearFiles()
      this.$emit('noBulkImportt', type)
    },
    submitUpload () {
      this.$refs.upload.submit()
    },
    downLoadFn () {
      window.location.href = this.Api + '/excel/demo.xlsx'
    },
    onChangeToolFile (file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]] // 这一步，是 展示最后一次选择的文件
      }
    },
    successResave (response, file, fileList) {
      if (response.msg.filed !== 0) {
        var msg = ''
        response.msg.errorData.forEach(element => {
          msg += element
        })
        this.$message.error(msg)
        this.$refs.upload.clearFiles()
        fileList.forEach(element => {
          element.status = 'ready'
        })
      } else {
        fileList.forEach(element => {
          element.status = 'success'
        })
        this.$message.success('导入成功')
        this.$refs.upload.clearFiles()
        this.close(1)
      }
    },
    errorResave (response, file, fileList) {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>
<style lang="scss">
.upload-demo,.el-upload{
  width: 100%;
}
</style>
<style lang="scss" scoped>
.uploadText{
  height: 40px;
  line-height: 40px;
}
</style>
